import { ref, onMounted } from 'vue';
// getPaginationInfo, setPagination, setLoading, tableData

export default function useDataSource(tableProps: any, info: any) {
  const { pagination, setPagination, setLoading, formRef } = info;
  const dataSource = ref<Recordable[]>([]);
  const request = tableProps.request;

  const fetch = async () => {
    const { pageSize, page } = pagination.value;
    await formRef.value?.validate();
    const searchValues = formRef.value?.getFieldsValue() ?? {};
    setLoading(true);
    const res = await request({
      size: pageSize,
      page,
      ...searchValues,
    });
    setLoading(false);
    setPagination({
      itemCount: res.total,
    });
    dataSource.value = res.data ?? [];
  };

  const reload = () => {
    fetch();
  };

  onMounted(() => {
    if (request) {
      fetch();
    }
  });

  return {
    dataSource,
    reload,
  };
}
